﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Eassets.Layered.Domain.Asset;
using Eassets.Service.Asset;
using Eassets.Service;
using System.Collections.ObjectModel;


namespace Eassets.UI.Asset
{
    public partial class CompanyAssetForm : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            AssetService assetService = new AssetService();
            if (!IsPostBack)
            {
                //GetAllAssets();
                GetAllMainCategory();
                gridViewAllAssets.DataSource = assetService.GetAllAssetsNotInCompanyAssets();
                gridViewAllAssets.DataBind();
                DataBindToGridViewMappedAssets();
            }
        }

        private void GetAllMainCategory()
        {
            dropDownListMainCategory.Items.Clear();
            CategoryService categoryService = new CategoryService();
            Category category = new Category();
            try
            {
                dropDownListMainCategory.DataSource = categoryService.GetAllAssetCategory().Where(x => x.ParentId == 0).ToList();

                dropDownListMainCategory.DataValueField = "CategoryId";
                dropDownListMainCategory.DataTextField = "Description";
                dropDownListMainCategory.DataBind();
            }
            catch (Exception exception)
            {
                throw;
            }
        }

        private void GetAllSubCategory()
        {
            dropDownListSubCategory.Items.Clear();
            CategoryService categoryService = new CategoryService();
            Category category = new Category();
            try
            {
                dropDownListSubCategory.DataSource = categoryService.GetAllAssetCategory().Where(x => x.ParentId == Convert.ToInt32(dropDownListMainCategory.SelectedValue)).ToList();

                dropDownListSubCategory.DataValueField = "CategoryId";
                dropDownListSubCategory.DataTextField = "Description";
                dropDownListSubCategory.DataBind();
            }
            catch (Exception exception)
            {
                throw;
            }
        }

        protected void dropDownListMainCategory_SelectedIndexChanged(object sender, EventArgs e)
        {
            GetAllSubCategory();

        }

        protected void dropDownListSubCategory_SelectedIndexChanged(object sender, EventArgs e)
        {
            GetAllAssetstoDropDown();
            //dropDownListSubCategory.SelectedIndex = 0;
        }

        protected void dropDownListAsset_SelectedIndexChanged(object sender, EventArgs e)
        {
            GetAllCompanyAssetByAssetId();

        }

        private void GetAllAssetstoDropDown()
        {
            dropDownListAsset.Items.Clear();
            AssetService assetService = new AssetService();
            Assets asset = new Assets();

            try
            {
                dropDownListAsset.DataSource = assetService.GetAllAsset().Where(x => x.AssetCategoryId == Convert.ToInt64(dropDownListSubCategory.SelectedValue));
                dropDownListAsset.DataValueField = "AssetId";
                dropDownListAsset.DataTextField = "Description";
                dropDownListAsset.DataBind();
            }
            catch (Exception exception)
            {

            }
        }

        private void GetAllCompanyAssetByAssetId()
        {
            CompanyAssetService companyAssetService = new CompanyAssetService();
            gridViewCompanyAssets.DataSource = companyAssetService.GetAllCompanyAssets().Where(x => x.AssetId == Convert.ToInt32(dropDownListAsset.SelectedValue)).ToList();
            gridViewCompanyAssets.DataBind();
        }


        private void GetAllAssets()
        {
            AssetService assetService = new AssetService();
            Assets asset = new Assets();

            try
            {

                gridViewAllAssets.DataSource = assetService.GetAllAsset();
                gridViewAllAssets.DataBind();

            }
            catch (Exception exception)
            {


            }
        }


        protected void buttonMap_Click(object sender, EventArgs e)
        {
            try
            {
                CompanyAssetService companyAssetService = new CompanyAssetService();
                Collection<CompanyAsset> companyAssets = new Collection<CompanyAsset>();


                Boolean isSelected = false;
                for (int count = 0; count < gridViewAllAssets.Rows.Count; count++)
                {
                    CheckBox check = (CheckBox)(gridViewAllAssets.Rows[count].FindControl("checkBoxAssets"));

                    if (check.Checked)
                    {
                        CompanyAsset companyAsset = new CompanyAsset();

                        if (gridViewAllAssets.Rows.Count > 0)
                        {
                            companyAsset.AssetId = Convert.ToInt32(gridViewAllAssets.Rows[
                                                             count].Cells[1].Text);
                        }

                        companyAsset.OrganizationLevelListId = Convert.ToInt32(2);

                        companyAsset.SysDateCreation = DateTime.Now;
                        companyAsset.SysDateLastModification = DateTime.Now;
                        companyAssets.Add(companyAsset);
                        isSelected = true;
                    }
                }

                if (isSelected)
                {

                    companyAssetService.MapAssetToCompanyAsset(companyAssets);
                    FlashMessage1.Message = "Successfully Saved";
                    FlashMessage1.CssClass = "okmessage";
                    FlashMessage1.Display();
                    GetAllAssets();

                    DataBindToGridViewMappedAssets();
                }
                else
                {
                    FlashMessage1.Message = "No records are selected";
                    FlashMessage1.CssClass = "errormessage";
                    FlashMessage1.Display();
                }
            }
            catch (Exception)
            {
                FlashMessage1.Message = "Saving Failed";
                FlashMessage1.CssClass = "errormessage";
                FlashMessage1.Display();
            }

            //GetUnmappedStakeholderGroupProperties();
            //GetMappedStakeholderGroupProperties();
            //updatePanelGrids.Update();

        }





        private void DataBindToGridViewMappedAssets()
        {
            Collection<CompanyAsset> companyAssets = new Collection<CompanyAsset>();
            CompanyAssetService companyAssetService = new CompanyAssetService();
            companyAssets = companyAssetService.GetMappedAssetByOrganizationLevelListId(Convert.ToInt16(1));
            gridViewCompanyAssets.DataSource = companyAssets;
            gridViewCompanyAssets.DataBind();
        }

        protected void buttonSave_Click(object sender, EventArgs e)
        {
            CompanyAssetService companyAssetService = new CompanyAssetService();
            CompanyAsset companyAsset = new CompanyAsset();

            if (Page.IsValid)
            {
                foreach (GridViewRow gridViewRow in gridViewCompanyAssets.Rows)
                {
                    if (((CheckBox)gridViewRow.Cells[0].FindControl("checkBoxAllSelect")).Checked)
                    {
                        companyAsset.OrganizationLevelListId = Convert.ToInt64(1);


                        companyAsset = companyAssetService.GetByIdCompanyAssets(Convert.ToInt64(gridViewRow.Cells[1].Text));

                        if (gridViewRow.Cells[2].Text != String.Empty)
                        {
                            companyAsset.AssetId = Convert.ToInt64(gridViewRow.Cells[2].Text);
                        }

                        companyAsset.IsAssetDepreciable = Convert.ToBoolean(
                           ((CheckBox)gridViewRow.Cells[3].FindControl("checkBoxIsDepriciate")).Checked
                        );


                        companyAsset.LifeTime = Convert.ToInt16(((TextBox)gridViewRow.Cells[4].FindControl("textBoxLifeTime")).Text);

                        companyAsset.LifeTimeUnitOfMeasureId = Convert.ToInt16(
                            ((DropDownList)gridViewRow.Cells[4].FindControl("dropDownListLifeTime")).SelectedValue);

                        companyAsset.DepreciationMethodId = Convert.ToInt16(
                            ((DropDownList)gridViewRow.Cells[5].FindControl("dropDownListDepMethod")).SelectedValue);

                        decimal depriciationRate;
                        String arrs = ((Label)gridViewRow.Cells[6].FindControl("labelDepreciationRate")).Text;
                        String[] arr = arrs.Split('%');
                        depriciationRate = Convert.ToDecimal(arr[0]);

                        companyAsset.DepreciationRate = depriciationRate;

                        companyAsset.ResidualValue = Convert.ToDecimal(
                            ((TextBox)gridViewRow.Cells[7].FindControl("textBoxResidualValue")).Text);

                        companyAsset.AssetSerialFormat = "";
                        companyAsset.Barcode = "";
                        companyAsset.SysDateCreation = DateTime.Now;
                        companyAsset.SysDateLastModification = DateTime.Now;
                    }
                }



            }
            try
            {
                companyAssetService.ModifyCompanyAssets(companyAsset);
                FlashMessage1.Message = "Successfully Saved";
                FlashMessage1.CssClass = "okmessage";
                FlashMessage1.Display();
               

                DataBindToGridViewMappedAssets();
            }
            catch (Exception)
            {
                FlashMessage1.Message = "Saving Failed";
                FlashMessage1.CssClass = "errormessage";
                FlashMessage1.Display();

            }

        }



        protected void gridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if (e.Row.DataItemIndex == 0 || ((Label)e.Row.Cells[7].FindControl("LabelHiddenLifeTimeUnitOfMeasure")).Text != String.Empty)
                {
                    ((DropDownList)e.Row.Cells[7].FindControl("dropDownListLifeTime")).SelectedValue = ((Label)e.Row.Cells[7].FindControl("LabelHiddenLifeTimeUnitOfMeasure")).Text.Trim();
                }
            }


            //gridViewCompanyAssets.Columns[1].Visible = false;
            //gridViewCompanyAssets.Columns[2].Visible = false;
        }

        protected void textBoxLifeTime_OnTextChange(object sender, EventArgs e)
        {
            TextBox txtBoxRow = (TextBox)sender;

            GridViewRow row = (GridViewRow)((TextBox)sender).Parent.Parent;

            if (row != null)
            {
                TextBox textBoxLifeTime = (TextBox)row.Cells[6].FindControl("textBoxLifeTime");

                DropDownList dropdownLifetimeUOM = (DropDownList)row.Cells[5].FindControl("dropDownListLifeTime");


                Label labelDepreciationRate = (Label)row.Cells[8].FindControl("labelDepreciationRate");

                decimal lifeTime = Convert.ToDecimal(textBoxLifeTime.Text);
                decimal depriciationRate;

                if ((dropdownLifetimeUOM.SelectedValue) == "2")
                {

                    depriciationRate = Math.Round(100 / ((lifeTime) / 12), 2);
                    labelDepreciationRate.Text = depriciationRate.ToString() + "%";
                }
                else
                {
                    depriciationRate = Math.Round((100 / lifeTime), 2);
                    labelDepreciationRate.Text = depriciationRate.ToString() + "%";

                }


                //labelTotal.Text =
                //    (Convert.ToInt32(txtBoxRow.Text) + Convert.ToInt32(textBoxTri2.Text) +
                //     Convert.ToInt32(textBoxTri3.Text)).ToString();



                //((TextBox)row.Cells[5].FindControl("textBoxTrimester2")).Focus();
            }
        }

        protected void gridViewCompanyAssets_PageIndexChanged(object sender, GridViewPageEventArgs e)
        {

            DataBindToGridViewMappedAssets();
            //  GetData(Convert.ToInt16(textBoxnoOfItems.Text), Convert.ToInt64(ViewState["AssetId"]), DataBindToGridView(), Convert.ToBoolean(ViewState["IsProcurement"]));
            gridViewCompanyAssets.PageIndex = e.NewPageIndex;
            gridViewCompanyAssets.DataBind();
        }

        protected void gridViewCompanyAssets_OnRowCreated(Object Sender, GridViewRowEventArgs e)
        {
            if (e.Row.Cells.Count > 1)
            {

                if (e.Row.Cells.Count > 1)
                {
                    e.Row.Cells[1].Visible = false;
                    e.Row.Cells[2].Visible = false;
                    e.Row.Cells[9].Visible = false;
                  
                }

            }
        }
    }
}